<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="登录" class="login-page-nav">
      <!-- 插槽后退按钮 -->
      <van-icon slot="left" name="cross" size="18" class="login-back" @click="$router.back()" />
    </van-nav-bar>
    <!-- 表单 -->
    <van-form @submit="onSubmit" ref="loginRef">
      <van-field
        v-model="user.mobile"
        name="mobile"
        placeholder="请输入手机号"
        type="number"
        maxlength="11"
        :rules="[{ required: true, message: '请填写手机号'},{validator:checkMobile,message:'手机号格式错误' }]"
      >
        <!-- 插槽，字体图标 -->
        <i slot="left-icon" class="iconfont iconshouji"></i>
      </van-field>
      <van-field
        v-model="user.code"
        name="验证码"
        placeholder="请输入验证码"
        type="number"
        maxlength="6"
        :rules="[{ required: true, message: '请填写验证码' },{validator:checkCode,message:'验证码格式错误' }]"
      >
        <i slot="left-icon" class="iconfont iconyanzhengma"></i>

        <template #button>
          <van-count-down
            :time="1000*10"
            v-if="showTimeout"
            @finish="showTimeout=false"
            format="ss s"
          />
          <!-- 倒计时 -->
          <van-button round class="yanzhengma" @click="sendCode" native-type="button" v-else>发送验证码</van-button>
        </template>
      </van-field>
      <div class="login-btn">
        <van-button block native-type="submit" class="login">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, getCode } from '../api/user'

export default {
  data() {
    return {
      user: { mobile: '', code: '246810' },
      mobileFormat: /^[1][3-9]\d{9}$/,
      codeFormat: /^\d{6}$/,
      // 倒计时显示
      showTimeout: false
    }
  },
  methods: {
    checkMobile(val) {
      // 验证手机号
      return this.mobileFormat.test(val)
    },
    checkCode(val) {
      // 验证验证码
      return this.codeFormat.test(val)
    },
    async onSubmit() {
      // 表单提交
      // 获取手机号和验证码
      this.$toast.loading({
        duration: 0, // 持续时间，0表示持续展示不停止
        forbidClick: true, // 是否禁止背景点击
        message: '登录中...' // 提示消息
      })
      try {
        const { data: res } = await login(this.user)
        console.log(res)
        this.$toast.success('登录成功')
        this.$store.commit('saveToken', res.data)
        // 跳转页面
        this.$router.push('/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败，手机号或验证码错误')
      }
    },
    async sendCode() {
      // 验证手机号，倒计时，发送验证码
      try {
        // 这个await要加，不然可能下个try先行
        await this.$refs.loginRef.validate('mobile')
        // 返回一个promise
      } catch (error) {
        return console.log('验证失败', error)
      }
      this.showTimeout = true
      // 配合倒计时finish事件
      try {
        await getCode(this.user.mobile)
        this.$toast('发送成功，请注意接收')
      } catch (err) {
        this.showTimeout = false
        // 接口限制，每分钟只能发一次
        if (err.response.status === 429) return this.$toast('验证码发送频繁')
        this.$toast('发送失败')
      }
    }
  }
}
</script>

<style lang='less' scoped>
.iconfont {
  font-size: 37px;
}
.yanzhengma {
  display: flex;
  height: 46px;
  font-size: 22px;
  line-height: 46px;
  background-color: #ededed;
  color: #666;
}
.login-btn {
  margin: 55px 33px;
  .login {
    background-color: #6db4fb;
  }
}
</style>
